// User类
import { reactive, ref, UnwrapRef } from "vue";
import { AuthenticationService } from "@/services/authentication.service";
import { User } from "@/models/User";
import { ElLoading } from "element-plus";

export default function login() {
  // ref 标签
  const loginFormRef = ref();
  // reactive 返回对象的响应式副本.
  const loginForm: UnwrapRef<User> = reactive<User>({
    username: "",
    password: "",
  });
  // 校验规则
  const loginFormRules = {
    username: [
      {
        required: true,
        message: "用户名不能为空",
        trigger: "blur",
      },
    ],
    password: [
      {
        required: true,
        message: "密码不能为空",
        trigger: "blur",
      },
    ],
  };
  const submit = () => {
    ElLoading.service({ text: "加载中..." });
    loginFormRef.value
      .validate()
      .then(() => {
        // 登录
        const { login } = new AuthenticationService();
        login(loginForm).then(() => {
          ElLoading.service().close();
        });
      })
      .catch((error: string) => {
        console.log("校验未通过");
        console.log("error", error);
        ElLoading.service().close();
      });
  };
  // 表单重置
  const resetForm = () => {
    loginFormRef.value.resetFields();
  };
  return {
    loginFormRef,
    loginForm,
    loginFormRules,
    submit,
    resetForm,
  };
}
